package elasticsearch.util;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.rest.RestStatus;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * 增删改查文档
 * @author jiangbang
 * @date 2017/7/27
 */
public class EsOperationIndexUtil {
    private static final String index = "index1";
    private static final String type = "type1";

    /**
     * 创建文档数据
     * @param client
     */
    public static void createIndex(TransportClient client) {
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("first_name","jiangbang");
        json.put("last_name","kimchy2");
        json.put("postDate",new Date());
        json.put("message","trying out Elasticsearch");

        IndexResponse response = client.prepareIndex(index, type)
                .setSource(json)
                .get();
        String _index = response.getIndex();
        String _type = response.getType();
        String _id = response.getId();
        long _version = response.getVersion();
        RestStatus status = response.status();
        System.out.println("_index:"+_index+"_type:"+_type+"_id"+_id+"_version"+_version+"status"+status);
    }
    /**
     * 通过ID删除指定文档数据
     * @param client
     */
    public static void deleteIndex(TransportClient client) {
        DeleteResponse response = client.prepareDelete(index, type, "AV2C4nad4JtjXDV7pPDP").get();
        System.out.println(response.status().getStatus());
    }

    /**
     * 通过条件过滤 删除指定文档数据
     * @param client
     */
    public static void DeleteByQueryIndex(TransportClient client) {
        BulkByScrollResponse response =
                DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
                        //过滤查询
                        .filter(QueryBuilders.matchQuery("first_name", "jiangbang"))
                        //指定索引
                        .source(index)
                        .get();
        long deleted = response.getDeleted();
        System.out.println(deleted);
    }

    /**
     * 修改数据
     * @param client
     */
    public static void UpdateIndex(TransportClient client) {
//        try {
//        UpdateRequest updateRequest = new UpdateRequest();
//        updateRequest.index(index);
//        updateRequest.type(type);
//        updateRequest.id("1");
//        updateRequest.doc(jsonBuilder()
//                .startObject()
//                .field("first_name", "jiang1")
//                .endObject());
//            client.update(updateRequest).get();
//
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }catch (IOException e) {
//            e.printStackTrace();
//        }

        try {
            client.prepareUpdate(index, type, "4")
                    .setDoc(jsonBuilder()
                            .startObject()
                            .field("first_name", "jiang4")
                            .field("age", "17")
                            .field("date", new Date())
                            .field("sex", "男")
                            .endObject())
                    .get();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 如果数据不存在，则插入IndexRequest的数据
     *
     * @param client
     */
    public static void InsertUpdateIndex(TransportClient client) {
        try{
            //待插入的数据
            IndexRequest indexRequest = new IndexRequest(index, type, "6")
                    .source(jsonBuilder()
                            .startObject()
                            .field("first_name", "jiang6")
                            .field("age", "18")
                            .field("date", new Date())
                            .field("sex", "男")
                            .endObject());
            //如果ID=4没有，则插入上面的数据，有则更新first_name
            UpdateRequest updateRequest = new UpdateRequest(index, type, "100")
                    .doc(jsonBuilder()
                            .startObject()
                            .field("first_name", "jiangbang4")
                            .endObject())
                    .upsert(indexRequest);
            client.update(updateRequest).get();
        }catch (IOException e){
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }


}
